package org.jetnuke.modules.blog;

import org.apache.log4j.Logger;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jforum.ActionServletRequest;
import net.jforum.JForumExecutionContext;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;

import net.jforum.util.legacy.commons.fileupload.FileItem;
import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.entities.BlogSettings;
import org.jetnuke.util.JetUtil;
import org.jetnuke.util.StringUtils;

public class UploadResource implements IAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(UploadResource.class);

	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - start"); //$NON-NLS-1$
		}

		if (ui == null || ui.getID() < 2)
			return null;
		String initPath = SystemGlobals
				.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR)
				+ "/blog/" + ui.getID() + "/";
		// String path = sc.getRealPath(initPath);
		File pathDir = new File(initPath);
		if (!pathDir.exists()) {
			pathDir.mkdirs();
		}

		ActionServletRequest asr = JForumExecutionContext.getRequest();
		FileItem file = (FileItem) asr.getObjectParameter("file");
		long fileSize = file.getSize();
		long resourcesSize = getResourcesSize(0, pathDir);
		BlogSettings bs = DataAccessDriver.getInst().newBlogSettingsDAO().get();
		boolean isSuperUser = ai != null && ai.isSuperUser();
		if (((resourcesSize + fileSize) > 1024 * bs.getLIMIT()) && !isSuperUser) {
			ActionForward returnActionForward = new ActionForward(info,
					"no_space.vm");
			if (logger.isDebugEnabled()) {
				logger
						.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
			}
			return returnActionForward;
		}

		String realName = file.getName();

		String simplifiedName = StringUtils.getSimpleFileName(realName);
		File f = new File(pathDir, simplifiedName);
		OutputStream outputStream = new BufferedOutputStream(
				new FileOutputStream(f));
		byte[] b = new byte[2048];
		BufferedInputStream inputStream = new BufferedInputStream(file
				.getInputStream());
		while ((inputStream.read(b)) != -1) {
			outputStream.write(b);
		}

		outputStream.flush();
		outputStream.close();
		inputStream.close();
		JetUtil.redirect(vc, response, request.getContextPath()
				+ "/do/blog/resources");

		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
		}
		return null;
	}

	public static long getResourcesSize(long initSize, File pathDir) {
		if (logger.isDebugEnabled()) {
			logger.debug("getResourcesSize(long, File) - start"); //$NON-NLS-1$
		}

		File f[] = pathDir.listFiles();
		long ret = initSize;
		for (int i = 0; i < f.length; i++) {
			if (f[i].isFile()) {
				ret = ret + f[i].length();
			} else {
				ret = getResourcesSize(ret, f[i]);
			}
		}

		if (logger.isDebugEnabled()) {
			logger.debug("getResourcesSize(long, File) - end"); //$NON-NLS-1$
		}
		return ret;
	}

}
